package com.Humanities.content.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @description 资源服务配置
 * @author Mr.M
 * @date 2022/10/18 16:33
 * @version 1.0
 */
@Configuration // 标注为配置类
@EnableResourceServer // 启用资源服务器
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) // 启用方法级别的安全注解
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {

    // 资源服务标识
    public static final String RESOURCE_ID = "xuecheng-plus";

    @Autowired // 自动注入 TokenStore
    TokenStore tokenStore;

//    @Bean
//    public UserDetailsService userDetailsService() {
//        //这里配置用户信息,这里暂时使用这种方式将用户存储在内存中
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
//        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
//        return manager;
//    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID) // 设置资源 ID
                .tokenStore(tokenStore) // 配置 TokenStore
                .stateless(true); // 设置为无状态
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 禁用 CSRF
                .authorizeRequests() // 配置请求授权
           //     .antMatchers("/r/**","/course/**").authenticated() // 所有 /r/** 的请求必须认证通过
                .anyRequest().permitAll(); // 允许所有请求
    }
    // Spring Security 中配置资源访问权限的部分，位于资源服务器或网关的 SecurityConfig 类中。

}